/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.k.server.service;

import com.alibaba.fastjson.JSON;
import com.weibo.api.motan.config.springsupport.annotation.MotanService;
import org.k.domain.UserInfo;
import org.k.dto.Result;
import org.k.api.IUserService;
import org.k.dto.UserInfoDto;
import org.k.mapper.UserMapper;
import org.k.server.cache.ICache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@MotanService
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Resource(name = "redisCache")
    private ICache redisCache;


    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    /**
     * 如果返回是String有bug，去找server端的toString方法
     * @param id
     * @return
     */
	@Override
	public UserInfoDto findUserById(String id) {
        logger.info("exec findUserById function.");
        UserInfo userInfo = redisCache.get("userInfo" + id, UserInfo.class);
        if(userInfo == null){
            logger.info("can't find object from cache.");
            userInfo = userMapper.findOne(id);
            logger.info("get object from db, the object is " + JSON.toJSONString(userInfo));
            redisCache.set("userInfo" + id, userInfo);
            logger.info("put the object to cache." );
        }else{
            logger.info("get object from cache.");
        }
        UserInfoDto ret = new UserInfoDto();
        BeanUtils.copyProperties(userInfo, ret);
		return ret;
	}

    @Transactional
    @Override
    public Result update(UserInfoDto userInfoDto) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoDto, userInfo);
        userMapper.update(userInfo);

        int i = 1/0;

        return new Result();

    }

}
